package com.ib.review.base.utils;

import com.ib.review.base.response.FileResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class UploadFiles {

    // 创建 RestTemplate 实例
    RestTemplate restTemplate = new RestTemplate();

    @Value("${file-system.username}")
    private String username;
    @Value("${file-system.password}")
    private String password;
    @Value("${file-system.upload-path}")
    private String uploadPath;
    @Value("${file-system.storage-id}")
    private String storageId;
    @Value("${file-system.upload-login}")
    private String uploadLogin;
    @Value("${file-system.upload-create}")
    private String uploadCreate;

    public void uploadWithRestTemplate(MultipartFile file, String filename, String onlineID) throws IOException {

        // 将文件内容一次性读取到内存（适合中小文件）
        byte[] fileBytes = file.getBytes(); // MultipartFile 提供的快捷方法
        ByteArrayResource fileResource = new ByteArrayResource(fileBytes) {
            @Override
            public String getFilename() {
                return file.getOriginalFilename();
            }
        };

        // 构造 multipart 请求体
        MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
        body.add("file", fileResource);       // 文件字段（与服务端参数名一致）

        // 4. 构造查询参数（URL 拼接）
        String uploadUrl = uploadPath + "?path=" + filename + "&storageId=" + storageId;

        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        headers.add("userOnlineID", onlineID);

        // 封装请求实体
        HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);

        // 发送POST请求
        restTemplate.exchange(
                uploadUrl,
                HttpMethod.POST,
                requestEntity,
                FileResponse.class
        );
    }

    public FileResponse getOnlineID() {
        // 使用Map构建JSON数据
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("userName", username);
        requestBody.put("password", password);
        requestBody.put("permission", 1);

        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        // 构建请求实体
        HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers);

        // 发送请求
        ResponseEntity<FileResponse> response = restTemplate.exchange(
                uploadLogin,
                HttpMethod.POST,
                requestEntity,
                FileResponse.class
        );
        return response.getBody();
    }

    public void createDirectory(String path,String onlineID) {
        path = "/" + username + path;
        // 构造请求 URL（拼接查询参数）
        String apiUrl = uploadCreate + "?path=" + path;

        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.add("userOnlineID", onlineID); // 必须的 Header

        // 构造请求实体（PUT 请求无需请求体，传 null）
        HttpEntity<String> requestEntity = new HttpEntity<>(null, headers);

        // 发送 PUT 请求
        restTemplate.exchange(
                apiUrl,
                HttpMethod.PUT,
                requestEntity,
                FileResponse.class
        );
    }
}
